package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.pickCar.PickCar;
import com.topisv.tms.entity.pickCar.PickCarStock;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.UserService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.pickCar.PickCarService;
import com.topisv.tms.service.pickCar.PickCarStockService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.service.work.WorkTaskService;

/**
 * 拣选车拣选任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/carPickTask" })
public class CarPickTaskController {

	private static final Logger logger = LoggerFactory.getLogger(CarPickTaskController.class);

	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private PickCarService pickCarService;
	@Autowired
	private PickCarStockService pickCarStockService;
	@Autowired
	private WorkTaskItemService workTaskItemService;
	@Autowired
	private UserService userService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	/**
	 * 导向拣选车拣选任务页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toCarPickTaskPage/{taskId}", method = RequestMethod.GET)
	public String toCarPickTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {
		    WorkTask  task=this.workTaskService.loadTaskById(taskId);
		    String taskCode=task.getTaskCode();
		    model.addAttribute("task", task);
		    
		    if(task.getStatus().equals("2")){ //任务未开始
		    	//查询空置拣选车
		    	Map<String, Object> param=new HashMap<String, Object>();
		    	param.put("warehouseCode", task.getWarehouseCode());
		    	param.put("status", "free");
			    List<PickCar> pickCarList=this.pickCarService.loadPickCarByParam(param);
			    model.addAttribute("pickCarList", pickCarList);
		    }
		    else if(task.getStatus().equals("11")){   //任务进行中
		    	//查询任务关联的拣选车
			    PickCar curPickCar=this.pickCarService.loadPickCarById(task.getPickcarId());  
			    model.addAttribute("curPickCar", curPickCar);
			    //车位信息
			    List<PickCarStock> curStockList=this.pickCarStockService.loadStockByCarId(task.getPickcarId()); 
			    model.addAttribute("curStockList", curStockList);
		    }
		    
		    //查询任务订单
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
		    
		    //拣货任务项
			Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=this.workTaskItemService.loadByParam(param1);
			model.addAttribute("taskItemList",taskItemList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "work/pick2th/carPickTask";
	}
	
	/**
	 * 绑定拣选车
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxBindCar")
	public void ajaxBindCar(@RequestParam(value = "carCode") String carCode, @RequestParam(value = "taskCode") String taskCode,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String msg=this.pickCarService.bindCar(carCode,taskCode,curUser.jobuuid); //任务绑定拣选车
			if("busy".equals(msg)){
				json.put("status","0");
				json.put("content","拣选车被占用");
			}
			else if("continue".equals(msg)){
				json.put("status","2");  //继续任务
				json.put("content","继续任务");
			}
			else if("unfixed".equals(msg)){
				json.put("status","3"); //拣选车编码和任务不匹配
				json.put("content","拣选车编码和任务不匹配");
			}
			else if("less".equals(msg)){
				json.put("status","4"); //车位不够
				json.put("content","车位不够");
			}
			else if("success".equals(msg)){
				json.put("status","1"); //成功绑定
				
				//拣选车
				PickCar pickCar=this.pickCarService.loadCarByCode(carCode);
				json.put("pickCar",pickCar);
				
				//拣选车位信息
				List<PickCarStock> stockList=this.pickCarStockService.loadStockByCarId(pickCar.getId());
				json.put("stockList",stockList);
				
				//订单信息
				Map<String, Object> param=new HashMap<String, Object>();
			    param.put("taskCode",taskCode);
			    param.put("billStatus", "0");
			    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			    json.put("orderList",orderList);
				
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("status","0");
			json.put("content","服务器异常");
		}
		out.print(json.toString());
	}
	
	
	/**
	 * ajax拣货&商品上车
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxPickAndSetGooods")
	public String ajaxPickAndSetGooods(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			String carCode=request.getParameter("carCode");
			Long taskId=Long.valueOf(request.getParameter("taskId"));
			String sku=request.getParameter("sku");
			Long taskItemId=Long.valueOf(request.getParameter("taskItemId"));
			
			//拣货
			String msg_pick=this.workTaskService.pick(taskItemId,sku);
			json.put("msg_pick", msg_pick);
			
			//上架
			if( "continue".equals(msg_pick) ||
				"finishing".equals(msg_pick) ||
				"task_finishing".equals(msg_pick)  ){
				
				PickCar pickCar=this.pickCarService.loadCarByCode(carCode);
				Map<String,String> result=this.pickCarService.setGoods(pickCar.getId(),sku,taskId);
				json.put("msg_up", result.get("msg"));  //返回信息
				json.put("stockCode", result.get("stockCode")); //返回拣选车位
				json.put("isFinished", result.get("isFinished")); //返回是否完全部上车
			}
			
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
		return null;
	}
	@RequestMapping(value = "ajaxOneKeyComplete")
	public String ajaxOneKeyComplete(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			Long taskId=Long.valueOf(request.getParameter("taskId"));
			
			logger.info("一键完成推车拣选开始--"+taskId);
			//一键完成推车拣选
			String returtString=workTaskService.pick(taskId);
			json.put("msg", returtString);
			logger.info("一键完成推车拣选结果--"+returtString);
			out.print(json);
			
		} catch (Exception e) {
			logger.error("error",e);
			if (e instanceof RedisSystemException) {
				json.put("msg", "recommit");//数据重新提交！
			} else {
				json.put("msg", "error");
			}
			out.print(json);
		}
		return null;
	}
	
	/**
	 * 新推车拣货--快捷领取
	 * @param taskId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toFastCarPickTaskPageNew/{taskId}/{flag}", method = RequestMethod.GET)
	public String v2_toFastCarPickTaskPageNew(@PathVariable("taskId") Long taskId, @PathVariable("flag") Long flag, Model model,RedirectAttributes redirectAttributes) {
		try {
		    WorkTask  task=workTaskService.loadTaskById(taskId);
		    String taskCode=task.getTaskCode();
		    model.addAttribute("task", task);
		    ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    model.addAttribute("loginerId", user.id);
		    if(task.getStatus().equals("1")){ //任务未开始 已分配拣货任务
		    	//查询空置拣选车
		    	Map<String, Object> param=new HashMap<String, Object>();
		    	param.put("warehouseCode", task.getWarehouseCode());
		    	param.put("customerCode", task.getCustomerCode());
		    	param.put("status", "free");
			    List<PickCar> pickCarList=pickCarService.loadPickCarByParam(param);
			    model.addAttribute("pickCarList", pickCarList);
		    }else if(task.getStatus().equals("11") && flag==1){
				redirectAttributes.addFlashAttribute("message", "该任务已被领取!");
				return "redirect:/pickTask/v2_toPickTaskListPage";
		    }
		    else if(task.getStatus().equals("11")){   //任务进行中
		    	//查询任务关联的拣选车
			    PickCar curPickCar=pickCarService.loadPickCarById(task.getPickcarId());  
			    model.addAttribute("curPickCar", curPickCar);
			    //车位信息
			    List<PickCarStock> curStockList=pickCarStockService.loadStockByCarId(task.getPickcarId()); 
			    model.addAttribute("curStockList", curStockList);
			    //查询拣货人
			    User curPickUser=userService.findOne(task.getPickerId());
			    model.addAttribute("curpickUser", curPickUser);
			    //查询指派人
			    User curAssignUser=userService.findOne(task.getAssignerId());
			    model.addAttribute("curAssignUser", curAssignUser);
			   
		    }
		    //根据查询拣货人
			List<User> userList=userService.findByWareHouseCodeAndCustomerCode(task.getWarehouseCode(),task.getCustomerCode() );
			model.addAttribute("userList", userList);
		    //查询任务订单
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    List<WorkOrder> orderList=workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
		    
		    //拣货任务项
			Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=workTaskItemService.loadByParam(param1);
			model.addAttribute("taskItemList",taskItemList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "work/pick2th/fastCarPickTask";
	}
	/**
	 *  新推车拣货--查询拣货车
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "searchPickCar", method = RequestMethod.POST)
	public String searchPickCar(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			List<PickCarStock> stockList=null;
			String carCode=request.getParameter("carCode");
			PickCar pickCar=pickCarService.loadCarByCode(carCode);
			if(StringUtils.equals(pickCar.getStatus(), "free")){
				json.put("pickCar", pickCar);
				json.put("status","1");//free 
				//拣选车位信息
				stockList=pickCarStockService.loadStockByCarId(pickCar.getId());
				json.put("stockList",stockList);
			}else{
				json.put("status","2");//busy
				json.put("msg","使用中，请选择其他拣选车!");
			}
			out.print(json);
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status", "3");
			json.put("msg", "error");
			out.print(json);
		}
		return null;
	}
	/**
	 *  新推车拣货--绑定拣货车
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxFastBindCar", method = RequestMethod.POST)
	public void ajaxFastBindCar(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		boolean isLockSuccess = false;
		String taskCode=request.getParameter("taskCode");
		try {
		    out = response.getWriter();
		    json = new JSONObject();
		    
		    isLockSuccess = workTaskService.lock("ajaxFastBindCar", taskCode, "-");
            if (!isLockSuccess) {
                json.put("status","0");
                json.put("content","该任务正在处理中，请核查！");
            }
            
			String carCode=request.getParameter("carCode");
			Long pickerId=Long.valueOf(request.getParameter("picker"));
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String msg=pickCarService.fastBindCar(carCode,taskCode,pickerId,curUser.jobuuid); //任务绑定拣选车
			if("errorStatue".equals(msg)){
			    json.put("status","0");
                json.put("content","作业状态异常,请核查!");
			}else if("busy".equals(msg)){
				json.put("status","0");
				json.put("content","拣选车被占用,请选择其他拣选车!");
			}
			else if("continue".equals(msg)){
				json.put("status","2");  //继续任务
				json.put("content","继续任务");
			}
			else if("unfixed".equals(msg)){
				json.put("status","3"); //拣选车编码和任务不匹配
				json.put("content","拣选车编码和任务不匹配");
			}
			else if("less".equals(msg)){
				json.put("status","4"); //车位不够
				json.put("content","车位不够");
			}
			else if("success".equals(msg)){
				json.put("status","1"); //成功绑定
				
				//拣选车
				PickCar pickCar=this.pickCarService.loadCarByCode(carCode);
				json.put("pickCar",pickCar);
				
				//拣选车位信息
				List<PickCarStock> stockList=this.pickCarStockService.loadStockByCarId(pickCar.getId());
				json.put("stockList",stockList);
				
				//订单信息
				Map<String, Object> param=new HashMap<String, Object>();
			    param.put("taskCode",taskCode);
			    param.put("billStatus", "0");
			    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			    json.put("orderList",orderList);
				
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("status","0");
			json.put("content","服务器异常或者该拣货已被使用");
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("ajaxFastBindCar", taskCode);
            }
            out.print(json.toString());
	    }
	}
	@RequestMapping(value = "updatePicker", method = RequestMethod.POST)
	public void updatePicker(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		boolean isLockSuccess = false;
		String taskCode=request.getParameter("taskCode");
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			isLockSuccess = workTaskService.lock("updatePicker", taskCode, "-");
            if (!isLockSuccess) {
                json.put("status","0");
                json.put("content","该任务正在处理中，请核查！");
            }
            
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			Long pickerId=Long.valueOf(request.getParameter("picker"));
			WorkTask workTask=workTaskService.loadTaskByCode(taskCode);
			workTask.setPickerId(pickerId);
			workTaskService.saveWorkTask(workTask);
			pickCarService.saveWorkLog(pickCarService.findUserByjobuuid(curUser.jobuuid), workTask,"11","快捷领取推车拣选进行中修改拣货人..("+workTask.getTaskCode()+")");
			json.put("status","success");
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status","error");
			json.put("content","服务器异常");
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("updatePicker", taskCode);
            }
            out.print(json.toString());
        }
	}
	/**
	 *新推车拣货-- 打印拣货单
	 */
	@RequestMapping(value = "printFastPickTask", method = RequestMethod.POST)
	public void printFastPickTask(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String pickerName="";
			String taskCode=request.getParameter("taskCode");
			List<WorkTaskItem> workTaskItemList=workTaskService.loadWorkTaskItem(taskCode);
			if(workTaskItemList != null && !workTaskItemList.isEmpty()){
				WorkTask workTask=workTaskService.loadTaskByCode(taskCode);
				if(null != workTask){
					workTaskService.updateTaskPrintFlag(taskCode, workTask.getPrintFlag()+1);
					workTaskService.updatePickInfo(taskCode);
					setAllocationDetail(workTaskItemList,workTask);
					  //查询指派人
					if(workTask.getPickerId()==null){
						pickerName="";
					}else{
						pickerName=userService.findOne(workTask.getPickerId()).getRealname(); 
					}
				}
				json.put("printFlag",workTask.getPrintFlag()+1);
				json.put("picker",pickerName);
				json.put("workTaskItemList",workTaskItemList);
				json.put("status","1");
			}else{
				json.put("status","0");
				json.put("content","拣货明细为空！");
			}
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("status","0");
			json.put("content","服务器异常或者该拣货已被使用");
		}
		out.print(json.toString());
	}
	private void setAllocationDetail(List<WorkTaskItem> workTaskItemList,WorkTask worktask){
		for(WorkTaskItem workTaskItem:workTaskItemList){
			// bug382 by zhangweize L481-L483   组合策略和大促策略不需要打箱位指引。
			if(!(StringUtils.equals(worktask.getTacticsType(), "comb") || StringUtils.equals(worktask.getTacticsType(), "promotion"))){
				workTaskItem.setAllocationDetail(getDetail(getStockInfo(workTaskItem), loadWorkOrderLike(workTaskItem)));
			}
			workTaskItem.setSkuName(getEdiGoodsSku(workTaskItem).getSkuName());
		}
	}
/**
 * 根据任务编码、库位信息模糊查询workOrder
 * @param workTaskItem
 * @return
 */
	private List<WorkOrder> loadWorkOrderLike(WorkTaskItem workTaskItem) {
		return workTaskService.loadWorkOrderLike(workTaskItem.getTaskCode(),getStockInfo(workTaskItem));
	}
/**
 * 根据箱位码、库位码、SKU拼装成箱位码_库位码_SKU
 * @param workTaskItem
 * @return
 */
	private String getStockInfo(WorkTaskItem workTaskItem) {
		return new StringBuilder()
				.append(workTaskItem.getStockCode()).append("_")
				.append(workTaskItem.getBoxCode()).append("_")
				.append(workTaskItem.getSku()).toString();
	}
	/**
	 * 根据客户编码、SKU查询商品信息
	 * @param workTaskItem
	 * @return
	 */
	private EdiGoodsSku getEdiGoodsSku(WorkTaskItem workTaskItem) {
		return ediGoodsSkuService.findByCustomerCodeAndSku(workTaskItem.getCustomerCode(), workTaskItem.getSku());
	}
/**
 * 获取箱位指引
 * @param stock_info
 * @param workOrderList
 * @return
 */
	private String getDetail(String stock_info, List<WorkOrder> workOrderList) {
		StringBuilder detail=new StringBuilder();
		for(WorkOrder workOrder:workOrderList){
			for(int i=0;i<getStockInfoArr(workOrder).length;i++){
				if(StringUtils.equals(stock_info, getStockOneSub(workOrder, i))){
					detail.append(workOrder.getRankno()).append("(").append(getStockInfoOneNum(workOrder, i)).append(")");
				}
			}
		}
		return detail.toString();
	}
	/**
	 * 截取stockInfo,得到数量
	 * @param workOrder
	 * @param i
	 * @return
	 */
	private String getStockInfoOneNum(WorkOrder workOrder, int i) {
		return getStockInfoArr(workOrder)[i].substring(getStockInfoArr(workOrder)[i].lastIndexOf("_")+1);
	}
	/**
	 * 截取stockInfo,得到箱位码_库位码_SKU
	 * @param workOrder
	 * @param i
	 * @return
	 */
	private String getStockOneSub(WorkOrder workOrder, int i) {
		return getStockInfoArr(workOrder)[i].substring(0,getStockInfoArr(workOrder)[i].lastIndexOf("_"));
	}
	/**
	 * stockinfo 获取
	 * @param workOrder
	 * @return
	 */
	private String[] getStockInfoArr(WorkOrder workOrder) {
		return workOrder.getStockInfo().split(";");
	}
	
	
}